package com.hdu.clj.dncard

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.hdu.clj.dncard.MainActivity
import com.hdu.clj.dncard.R
import com.hdu.clj.dncard.database.UserDatabase
import com.hdu.clj.dncard.databaseUtil.UserDatabaseUtil
import com.hdu.clj.dncard.util.ActivityCollector
import com.hdu.clj.dncard.util.EquipInit
import com.hdu.clj.dncard.util.MonsterInit
import kotlinx.android.synthetic.main.activity_login.*
import java.io.*

class LoginActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        ActivityCollector.addActivity(this)

        val startIcon = Typeface.createFromAsset(assets,"iconfont.ttf")

        toReg.setTypeface(startIcon)
        toReg.setText(R.string.reg)
        startSport.setTypeface(startIcon)
        startSport.setText(R.string.start)

        if (load("remAcc").isNotEmpty()&&load("remPass").isNotEmpty()&&load("isRem").isNotEmpty()&&load("isRem").equals("true")){
            val remAcc = load("remAcc")
            val remPass = load("remPass")
            nameLog.setText(remAcc)
            passLog.setText(remPass)
            rememberMe.isChecked = true

        }
        val userAcc = nameLog.text
        val userPass = passLog.text
        var ver = 1
        //点击开始运动按钮
        startSport.setOnClickListener {
            val dbUser = UserDatabase(this,"Users.db",1)
            val dbu = dbUser.writableDatabase
            //获取数据表的版本号
//            if (load("ver").isNotEmpty()){
//                ver = load("ver").toInt()
//            }
            //检查用户名或密码输入是否为空
            if (userAcc.isNotEmpty()&&userPass.isNotEmpty()) {
                //查找用户是否已经注册
                val sname = dbu.rawQuery("select * from Users where acc = ?", arrayOf(userAcc.toString()))
                if (sname.moveToFirst()) {
                    //检查密码是否正确
                    val spass = sname.getString(sname.getColumnIndex("pass"))
                    /**
                     * 检查密码是否正确
                     */
                    if (userPass.toString().equals(spass)){
                        /**
                         * 记住用户账号和登录密码
                         * isChecked
                         * true 记住
                         * false 不记住
                         */
                        if (rememberMe.isChecked){
                            save(userAcc.toString(),"remAcc")
                            save(userPass.toString(),"remPass")
                            save("true","isRem")
                            rememberMe.isChecked = true
                        }
                        else{
                            save("false","isRem")
                        }
                        /**
                         * 将当前用户账号保存在本地
                         */
                        save(userAcc.toString(),"userAcc")
                        /**
                         * 加载装备与怪物
                         */
                        EquipInit().equipinit(this,1)
                        MonsterInit().moninit(this)
                        if (UserDatabaseUtil().isCreate(this,userAcc.toString())==0){
                            val intent = Intent(this, CreateHeroActivity::class.java)
                            startActivity(intent)
                        }
                        else{
                            val intent = Intent(this, MainActivity::class.java)
                            startActivity(intent)
                        }

                    }
                    else{
                        passLog.text.clear()
                        Toast.makeText(this, "密码错误，请重新输入!", Toast.LENGTH_SHORT).show()
                    }
                }
                else{
                    nameLog.text.clear()
                    passLog.text.clear()
                    Toast.makeText(this, "用户未注册!", Toast.LENGTH_SHORT).show()
                }
            }
            else{
                Toast.makeText(this, "请输入完整的用户信息!", Toast.LENGTH_SHORT).show()
            }

        }
        //注册页面
        toReg.setOnClickListener {
            val intent = Intent(this,RegActivity::class.java)
            startActivity(intent)
        }

    }
    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }
    private fun save(inputText: String,data:String) {
        try {
            val output = openFileOutput(data, Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(inputText)
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
    }

    private fun load(data:String): String {
        val content = StringBuilder()

        try {
            val input = openFileInput(data)
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        }catch (e:IOException){
            e.printStackTrace()
        }
        return content.toString()
    }
}
